<template>
  <div>
    <div>
      <el-form ref="dataForm" label-width="150px" label-position="left" :rules="rules" :model="temp" >
        <el-form-item label="后端项目路径" prop="javaProjectPath">
          <el-input v-model="temp.javaProjectPath" clearable type="mini"/>
        </el-form-item>
        <el-form-item label="前端项目路径" prop="vueProjectPath">
          <el-input v-model="temp.vueProjectPath" clearable type="mini"/>
        </el-form-item>
        <el-form-item label="包路径(group)" prop="packageDotParent">
          <el-input v-model="temp.packageDotParent" clearable type="mini" placeholder="包的group路径，就是包的前部分，代码中包结构: group.微服务名.modules.领域名称；如：com.rt.easyjava。"/>
        </el-form-item>
        <el-form-item label="微服务名" prop="moduleName">
          <el-input v-model="temp.moduleName" placeholder="如: base、city、cityflow..." clearable type="mini"/>
        </el-form-item>
        <el-form-item label="领域名称" prop="domainName">
          <el-input v-model="temp.domainName" placeholder="微服务里的子领域，如: timerjob (生成源码路径：.../core/biz/timerjob)" clearable type="mini"/>
        </el-form-item>
        <el-form-item label="包名">
          {{temp.packageDotParent}}.{{temp.moduleName}}.modules.{{temp.domainName}}
        </el-form-item>
        <el-form-item label="表名" prop="mistTablename">
          <el-input v-model="temp.mistTablename" placeholder="1，单表：t_user；2，匹配多表：t_*；3，分号分隔多表: t_user;t_company"  type="mini"/>
        </el-form-item>
        <el-form-item label="去除表前缀" prop="stripPrefix">
          <el-input v-model="temp.stripPrefix" placeholder="选填项；不去除话，默认为空就好了；去除表的前缀t_，则输入: t_"  type="mini"/>
        </el-form-item>
      </el-form>
    </div>
    <span style="font-size: 13px;">
      注：数据表加comment, 会在代码中自动加入注解；字段comment，以";"分隔，";"之前部分，自动作为属性名称。
    </span>
    <br/>
    <br/>
    <div>
      <el-button type="primary" @click="handlePreview">扫库生成预览菜单</el-button>
      <el-button type="primary" @click="handleBuildCode(1)">扫库生成预览+源码(简单模式)</el-button>
      <!--<el-button type="primary" @click="handleBuildCode(2)">扫库生成预览+源码(继承模式)</el-button>-->
    </div>

    <br>
    <div>{{ logsHead }}</div>
    <div v-for="(logTable,index) in logTableList" :key="index">
      <p>{{ logTable.tableName }}</p>
      <div v-for="(log,i) in logTable.logs" :key="i">
        <span style="line-height:20px; margin-left: 10px;">{{ log.content }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import {buildCodeApi, addTemplatetableApi, addTemplatetableColumnApi, gen2LevelMenuApi} from './api/tmpt-list-api'
import StorageUtil from "@/utils/StorageUtil";
export default {
  name: 'BuildCode',
  data() {
    return {
      temp: {
        vueProjectPath: undefined,
        javaProjectPath: undefined,
        packageDotParent: undefined,
        moduleName: undefined,
        domainName: undefined,
        stripPrefix: undefined,
        mistTablename: undefined
      },
      logsHead: '',
      logTableList: [
        /* { tableName: 'test_logs1',
          logs: [
            { content: 'log11' },
            { content: 'log12' }]
        }*/
      ],
      preview_menu_id: 667,
      coding_menu_id: 668,
      rules: {
        vueProjectPath: [{ required: true, message: 'required', trigger: 'blur' }],
        javaProjectPath: [{ required: true, message: 'required', trigger: 'blur' }],
        packageDotParent: [{ required: true, message: 'required', trigger: 'blur' }],
        moduleName: [{ required: true, message: 'required', trigger: 'blur' }],
        domainName: [{ required: true, message: 'required', trigger: 'blur' }],
        mistTablename: [{ required: true, message: 'required', trigger: 'blur' }],
      },
    }
  },
  mounted() {
    this.loadLocalPath()
  },
  methods: {
    loadLocalPath() {
      // load path
      let generatorParamPath = StorageUtil.readObj("generatorParamPath")
      this.temp.vueProjectPath = generatorParamPath.vueProjectPath
      this.temp.javaProjectPath = generatorParamPath.javaProjectPath
      //load module
      let generatorParamModule = StorageUtil.readObj("generatorParamModule")
      this.temp.moduleName = generatorParamModule.moduleName
      this.temp.packageDotParent = generatorParamModule.packageDotParent
    },
    savePathToLocal() {
      // save path
      let generatorParamPath = {}
      generatorParamPath.vueProjectPath = this.temp.vueProjectPath
      generatorParamPath.javaProjectPath = this.temp.javaProjectPath
      StorageUtil.save("generatorParamPath", generatorParamPath, false)
      // save module
      let generatorParamModule = {}
      generatorParamModule.moduleName = this.temp.moduleName
      generatorParamModule.packageDotParent = this.temp.packageDotParent
      StorageUtil.save("generatorParamModule", generatorParamModule, false)
    },
    // 源码模式
    handleBuildCode(codeType) {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.savePathToLocal()
          this.buildCode('code', codeType)
        }
      })
    },
    // 预览模式
    handlePreview() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.savePathToLocal()
          this.buildCode('')
        }
      })
    },
    buildCode(mode, codeType) {
      let param = {}
      param.vueProjectPath = this.temp.vueProjectPath
      param.javaProjectPath = this.temp.javaProjectPath
      param.packageDotParent = this.temp.packageDotParent
      param.moduleName = this.temp.moduleName
      param.domainName = this.temp.domainName
      param.mistTablename = this.temp.mistTablename
      param.stripPrefix = this.temp.stripPrefix

      buildCodeApi(param).then(result => {
        let resultList = result.list
        let resultListLen = resultList.length
        this.logsHead = '共发现' + resultListLen + '张表进行处理'
        this.logTableList = []

        for (let i = 0; i < resultListLen; i++) {
          const table = resultList[i]
          const tableName = table.tableName
          // initLogs(tableName)
          this.logTableList.push({ tableName: tableName })
        }

        // 调用业务接口
        for (let i = 0; i < resultListLen; i++) {
          const table = resultList[i]
          // const tableName = table.tableName
          // let primaryKey = table.primaryKey
          // showInLogs(tableName, tableName)
          // add template table
          this.addTemplatetable(table, mode, codeType)
        }
      })
    },

    // add template table
    addTemplatetable(table, mode, codeType) {
      const tableName = table.tableName
      const primaryKey = table.primaryKey
      const data = {}
      data.codeType = codeType
      data.keyRandom = tableName + '_' + Math.floor(Math.random() * 100000000)
      data.tableName = tableName
      data.tableNameShow = tableName
      data.primaryKey = primaryKey
      data.foreignKey = ''
      data.mode = 1
      data.tableAliasName = 't1'
      data.hasAddBtn = 1
      data.hasDownloadReportBtn = 1
      data.hasEditBtn = 2
      data.hasHistoryBtn = 0
      data.tableNameSql = tableName + ' t1'
      data.width4AddDialog = 0
      data.height4AddDialog = 0
      data.style4AddDialog = 'width:700px;height:500px;'
      data.isdialog4AddDialog = 1
      data.hasCheckbox = 0
      data.deleteFlag = 0
      data.chartWidth = 0
      data.chartHeight = 0
      data.idType = 'auto'
      data.btnMulti = '[1, 2, 3, 4, 5]'
      data.treeJson = '{\n' +
        '  "tree": {\n' +
        '    "desc": "树结构，默认是自动寻找‘表名_id’字段作外键，生成自关联树",\n' +
        '    "enable": false,\n' +
        '    "label": "name"\n' +
        '  },\n' +
        '  "otm": {\n' +
        '    "desc": "OneToMany: 一对多中子表信息; 多子表时，otm传入json数组； column: 主表的关联字段，默认是ID; slaveColumn子表字段，外键。",\n' +
        '    "column": "id",\n' +
        '    "enable": false,\n' +
        '    "slaveTableName": "tmpt_auth_user",\n' +
        '    "slaveColumn": "tmpt_auth_user_id"\n' +
        '  },\n' +
        '  "asideTree": {\n' +
        '    "desc": "左树右列表结构：左树是主表，右列表是子表",\n' +
        '    "enable": false,\n' +
        '    "fatherTableName": "",\n' +
        '    "sonTableName": "tmpt_auth_user"\n' +
        '  }\n' +
        '}'
      addTemplatetableApi(data).then(result => {
        const responseCode = result.code
        const responseContent = result.content
        const a1TemplateTableId = result.map.a1TemplateTableId
        this.showInLogs("增加'模板表'结果：" + responseContent + '   a1TemplateTableId=' + a1TemplateTableId, tableName, responseCode)
        // add template table coloumn
        this.addTemplatetableColumn(a1TemplateTableId, data, mode)
      })
    },
    // 日志框 清空
    clearLogs() {
      this.logTableList = []
    },

    // add template table column
    addTemplatetableColumn(a1TemplateTableId, data1, mode) {
      var data = {}
      data._id = a1TemplateTableId
      addTemplatetableColumnApi(data).then(result => {
        this.showInLogs("'模板列'自动扫库结果：" + result.content, data1.tableName, result.code)

        // generator 2 level menu 预览模式
        // 627 is 预览菜单的 menuId
        this.gen2LevelMenu('datagrid', '预览模式', data1.tableName + '_', this.preview_menu_id, a1TemplateTableId, data1)

        // generator 2 level menu 源码模式
        // 628 is 源码菜单的 menuId
        if (mode === 'code') {
          this.gen2LevelMenu('datagrid-sourcecode', '源码模式', data1.tableName, this.coding_menu_id, a1TemplateTableId, data1)
        }
      })
    },
    // generator 2 level menu
    gen2LevelMenu(pageType, modeStr, menu2Name, menu1Id, a1TemplateTableId, data1) {
      const data = {
        'codeType': data1.codeType,
        'menu1Id': menu1Id,
        'temptTableId': a1TemplateTableId,
        'pageType': pageType,
        'menu2Name': menu2Name,
        'keyRandom': data1.keyRandom,
        'genType':0,
        'vueProjectPath': this.temp.vueProjectPath,
        'javaProjectPath': this.temp.javaProjectPath,
        'packageDotParent': this.temp.packageDotParent,
        'stripPrefix': this.temp.stripPrefix,
        'moduleName' : this.temp.moduleName,
        'domainName' : this.temp.domainName
      }
      gen2LevelMenuApi(data).then(result => {
        this.showInLogs(modeStr + ':生成结果：' + result.content, data1.tableName, result.code)
      })
    },

    // 日志框 加入信息
    showInLogs(text, tableName, responseCode) {
      this.logTableList.forEach((item, index, _self) => {
        if (item.tableName === tableName) {
          let logs = []
          if (item.logs !== undefined) {
            logs = item.logs
          }
          const log = {}
          log.content = text
          logs.push(log)

          item.logs = logs
          this.$forceUpdate()

          return
        }
      })
      // 失败了
      /* if (responseCode === 0) {
        $('#' + tableName).append('<span style="line-height:20px; color: #ff6252;">' + text + '</span><br/>')
      } else {
        $('#' + tableName).append('<span style="line-height:20px;">' + text + '</span><br/>')
      }*/
    }
    /*,
    // init a div content, the id is "tablename"
    initLogs(tableName) {
      $('#logsDiv').append("<div id='" + tableName + "' style='border:1px solid #dddddd; margin:3px;padding:3px;'  />")
    },
    showInLogsHead(text) {
      $('#logsHead').append('<span style="line-height:20px;">' + text + '</span><br/>')
    }
    */

  }
}
</script>

<style scoped>

</style>
